﻿using Game.Entity.Accounts;
using Game.Entity.Treasure;
using Game.Facade;
using Game.Kernel;
using Game.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;

namespace Yule8xModel
{
    public class WanghuGameUtil
    {
        public static GameUserInfoModel GetGameUserInfo(int game_id, string unionid=null)
        {
            string where = null;
            if (!string.IsNullOrEmpty(unionid))
            {
                where = string.Format("UserUin='{0}'",unionid);
            }
            if (game_id > 0)
            {
                where = string.Format("GameID={0}", game_id);
            }
            if (string.IsNullOrEmpty(where))
            {
                return null;
            }
            GameUserInfoModel model = null;
            string sqlstmt = string.Format("SELECT UserID,GameID,Accounts,NickName  FROM [RYAccountsDB].[dbo].[AccountsInfo] WHERE {0};", where);
            DataTable dtUser = DbFactory.Init(AppInfo.con_wanghu).ExecuteDataTable(sqlstmt);
            if (dtUser.Rows.Count > 0)
            {
                model = new GameUserInfoModel();
                model.UserID = DataTableUtil.GetInteger(dtUser, "UserID");
                model.GameID = DataTableUtil.GetInteger(dtUser, "GameID");
                model.Accounts = DataTableUtil.GetString(dtUser, "Accounts");
                model.NickName = DataTableUtil.GetString(dtUser, "NickName");
            }
            return model;
        }
        // 失败返回空字符串
        public static string GetNickName(int game_id)
        {
            string sqlstmt = string.Format("select NickName from [RYAccountsDB].[dbo].[AccountsInfo] where GameID={0}", game_id);
            object value = DbFactory.Init(AppInfo.con_wanghu).GetValue(sqlstmt);
            return null == value ? string.Empty : value.ToString();
        }
        /// <summary>
        /// 获取游戏GameID
        /// </summary>
        /// <param name="unionid"></param>
        /// <returns></returns>
        public static int GetGameID(string unionid)
        {
            if (string.IsNullOrEmpty(unionid))
            {
                return 0;
            }
            string sqlstmt = string.Format("select GameID from [RYAccountsDB].[dbo].[AccountsInfo] where [UserUin]='{0}';", unionid);
            string value = DbFactory.Init(AppInfo.con_wanghu).GetValue(sqlstmt, "0").ToString();
            return StringUtil.ToInteger(value);
        }
        
        public static bool CheckGameId(int game_id)
        {
            string sqlstmt = string.Format("select count(0) from [RYAccountsDB].[dbo].[AccountsInfo] where GameID ={0}", game_id);
            int count = DbFactory.Init(AppInfo.con_wanghu).ExecuteCount(sqlstmt);
            return count > 0;
        }
        /// <summary>
        /// 写入MoneyValue表
        /// <para>返回记录ID</para>
        /// </summary>
        /// <param name="number"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static int CheckMoneyValue(decimal amount)
        {
            // 如果moneyvalue数量不存在，则先往库里面写入一条记录
            string sqlstmt = "select WebID from RYTreasureDB.dbo.GlobalWebInfo where Price=" + amount;
            LogUtil.Instance.WriteInfo("[网狐游戏-游戏币表] " + sqlstmt);
            object oid = DbFactory.Init(AppInfo.con_wanghu).GetValue(sqlstmt);
            if (null == oid)
            {
                sqlstmt = string.Format("INSERT INTO RYTreasureDB.dbo.GlobalWebInfo (ProductName, ProductType, Price, PresentCurrency, CollectDate) VALUES ('微信官方充值',805,{0},{0},'{1}')", amount, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                LogUtil.Instance.WriteInfo("[网狐游戏-游戏币表] " + sqlstmt);
                DbFactory.Init(AppInfo.con_wanghu).ExecuteNonQuery(sqlstmt);
            }
            return null == oid ? 0 : int.Parse(oid.ToString());
        }
        public static DataTable GetMoneyValueTable(string idField = "ID", string valueField = "Value", string textField = "Wallet", int limit=6)
        {
            string sqlstmt = string.Format("SELECT top {3} WebID as {0}, Price as {1}, PresentCurrency as {2} FROM RYTreasureDB.dbo.GlobalWebInfo WHERE ProductType=805 and Price > 1 order by id", idField, valueField, textField,limit);
            DataTable dtList = DbFactory.Init(AppInfo.con_wanghu).ExecuteDataTable(sqlstmt);
            if (dtList.Rows.Count < 1)
            {
                int[] initNumbers = new int[] { 10, 50, 100, 300, 500, 1000 };
                IList<string> list = new List<string>();
                string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                foreach (int num in initNumbers)
                {
                    list.Add(string.Format("('微信官方充值',805,{0},{0},'{1}')", num, timestamp));
                }
                string sqlstmt2 = "INSERT INTO RYTreasureDB.dbo.GlobalWebInfo (ProductName,ProductType,Price,PresentCurrency,CollectDate) VALUES " + string.Join(",", list);
                DbFactory.Init(AppInfo.con_wanghu).ExecuteNonQuery(sqlstmt2);
                dtList = DbFactory.Init(AppInfo.con_wanghu).ExecuteDataTable(sqlstmt);
            }
            return dtList;
        }

        public static bool UpdateYouxidou(int wanghu_user_id, string strAccounts, decimal amount, out string error)
        {
            // 支付方法
            string orderid = PayHelper.GetOrderIDByPrefix("WX");
            OnLineOrder onlineOrder = new OnLineOrder();
            onlineOrder.ShareID = 402;
            onlineOrder.OrderID = orderid;


            onlineOrder.OperUserID = wanghu_user_id;
            onlineOrder.Accounts = strAccounts;
            onlineOrder.OrderAmount = amount;
            onlineOrder.IPAddress = GameRequest.GetUserIP();

            //生成订单
            Message umsg = RequestOrder(onlineOrder, 805, 2);
            if (!umsg.Success)
            {
                error = umsg.Content;
                return false;
            }
            // 支付回调
            ShareDetialInfo detailInfo = new ShareDetialInfo();
            detailInfo.OrderID = orderid;
            detailInfo.IPAddress = Utility.UserIP;
            detailInfo.PayAmount = amount;
            umsg = FilliedOnline(detailInfo, 0);
            error = umsg.Content;
            return umsg.Success;
        }


        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public static Message RequestOrder(OnLineOrder orderInfo, int productType, int appID)
        {
            string return_id = string.Empty;
            DbFactory.Init(AppInfo.con_wanghu, true);
            DbParams dbParams = DbFactory.CreateParams();
            dbParams.AddInputInteger("dwOperUserID", orderInfo.OperUserID);
            dbParams.AddInputInteger("dwShareID", orderInfo.ShareID);
            dbParams.AddInputString("strAccounts", orderInfo.Accounts);
            dbParams.AddInputString("strOrderID", orderInfo.OrderID);
            dbParams.AddInputDecimal("dcOrderAmount", orderInfo.OrderAmount);
            dbParams.AddInputInteger("dwProductType", productType);
            dbParams.AddInputInteger("dwAppID", appID);
            dbParams.AddInputString("strIPAddress", orderInfo.IPAddress);
            dbParams.AddOutput<string>("strErrorDescribe");
            dbParams.AddReturn("@return");

            System.Data.Common.DbParameter[] outParams = DbFactory.Init(AppInfo.con_wanghu).ExecuteProcedureNonQuery("RYTreasureDB.dbo.NET_PW_ApplyOnLineOrder", dbParams.ToArray());
            string msg = string.Empty;
            foreach (System.Data.Common.DbParameter p in outParams)
            {
                if (p.ParameterName == "@return")
                {
                    return_id = p.Value.ToString();
                    continue;
                }
                if (p.ParameterName == "strErrorDescribe")
                {
                    msg = p.Value.ToString();
                    continue;
                }
            }
            return new Message() { Success = return_id == "0", Content = msg };
        }

        /// <summary>
        /// 网狐游戏豆在线充值
        /// </summary>
        /// <param name="olDetial"></param>
        /// <returns></returns>
        public static Message FilliedOnline(ShareDetialInfo olDetial, int isVB)
        {
            string return_id = string.Empty;
            DbFactory.Init(AppInfo.con_wanghu, true);
            DbParams dbParams = DbFactory.CreateParams();

            dbParams.AddInputString("strOrdersID", olDetial.OrderID);
            dbParams.AddInputDecimal("PayAmount", olDetial.PayAmount);
            dbParams.AddInputInteger("isVB", isVB);
            dbParams.AddInputString("strIPAddress", olDetial.IPAddress);
            dbParams.AddOutput<string>("strErrorDescribe");
            dbParams.AddReturn("@return");

            System.Data.Common.DbParameter[] outParams = DbFactory.Init(AppInfo.con_wanghu).ExecuteProcedureNonQuery("RYTreasureDB.dbo.NET_PW_FilledOnLine", dbParams.ToArray());
            string msg = string.Empty;
            foreach (System.Data.Common.DbParameter p in outParams)
            {
                if (p.ParameterName == "@return")
                {
                    return_id = p.Value.ToString();
                    continue;
                }
                if (p.ParameterName == "strErrorDescribe")
                {
                    msg = p.Value.ToString();
                    continue;
                }
            }
            return new Message() { Success = return_id == "0", Content = msg };
        }

        // =======================================


        public static bool UpdateRoomCard(int game_id, int dimond_number, int user_id, int pay_id, decimal amount, out string error)
        {
            // 支付方法
            string orderID = PayHelper.GetOrderIDByPrefix("WapWX");
            OnLineOrder onlineOrder = new OnLineOrder();
            onlineOrder.ShareID = 81;
            onlineOrder.OrderID = orderID;

            onlineOrder.OperUserID = user_id;
            onlineOrder.GameID = game_id;
            onlineOrder.OrderAmount = amount;
            onlineOrder.IPAddress = GameRequest.GetUserIP();

            //生成订单
            Message umsg = RequestOrderFK(onlineOrder, pay_id);
            if (!umsg.Success)
            {
                error = umsg.Content;
                return false;
            }

            // 确认订单
            ShareDetialInfo detailInfo = new ShareDetialInfo();
            detailInfo.OrderID = orderID;
            detailInfo.IPAddress = Utility.UserIP;
            detailInfo.PayAmount = amount;
            umsg = FilliedOnlineFK(detailInfo, 0);
            LogUtil.Instance.WriteInfo("[WanghuGameUtil-UpdateRoomCard] " + umsg.Content);
            error = umsg.Content;
            return umsg.Success;
        }
        /// <summary>
        /// 生成房卡订单
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public static Message RequestOrderFK(OnLineOrder orderInfo, int configID)
        {
            string return_id = string.Empty;
            DbFactory.Init(AppInfo.con_wanghu, true);
            DbParams dbParams = DbFactory.CreateParams();
            dbParams.AddInputInteger("dwOperUserID", orderInfo.OperUserID);
            dbParams.AddInputInteger("dwShareID", orderInfo.ShareID);
            dbParams.AddInputInteger("dwGameID", orderInfo.GameID);
            dbParams.AddInputString("strOrderID", orderInfo.OrderID);
            dbParams.AddInputInteger("dwConfigID", configID);
            dbParams.AddInputString("strIPAddress", orderInfo.IPAddress);
            dbParams.AddOutput<string>("strErrorDescribe");
            dbParams.AddReturn("@return");
            System.Data.Common.DbParameter[] outParams = DbFactory.Init(AppInfo.con_wanghu).ExecuteProcedureNonQuery("RYTreasureDB.dbo.NET_PW_ApplyOnLineOrderFK", dbParams.ToArray());
            string msg = string.Empty;
            foreach (System.Data.Common.DbParameter p in outParams)
            {
                if (p.ParameterName == "@return")
                {
                    return_id = p.Value.ToString();
                    continue;
                }
                if (p.ParameterName == "@strErrorDescribe")
                {
                    msg = p.Value.ToString();
                    continue;
                }
            }
            return new Message() { Success = return_id == "0", Content = msg };
        }

        /// <summary>
        /// 在线房卡充值
        /// </summary>
        /// <param name="olDetial"></param>
        /// <returns></returns>
        public static Message FilliedOnlineFK(ShareDetialInfo olDetial, int isVB)
        {
            string return_id = string.Empty;
            DbFactory.Init(AppInfo.con_wanghu, true);
            DbParams dbParams = DbFactory.CreateParams();
            dbParams.AddInputString("strOrdersID", olDetial.OrderID);
            dbParams.AddInputDecimal("PayAmount", olDetial.PayAmount);
            dbParams.AddInputString("strIPAddress", olDetial.IPAddress);
            dbParams.AddOutput<string>("strErrorDescribe");
            dbParams.AddReturn("@return");
            System.Data.Common.DbParameter[] outParams = DbFactory.Init(AppInfo.con_wanghu).ExecuteProcedureNonQuery("RYTreasureDB.dbo.NET_PW_FilledOnLineFK", dbParams.ToArray());
            string msg = string.Empty;
            foreach (System.Data.Common.DbParameter p in outParams)
            {
                if (p.ParameterName == "@return")
                {
                    return_id = p.Value.ToString();
                    continue;
                }
                if (p.ParameterName == "@strErrorDescribe")
                {
                    msg = p.Value.ToString();
                    continue;
                }
            }
            return new Message() { Success = return_id == "0", Content = msg };
        }
    }
}
